/*
	The MIT License

	Copyright (c) 2008 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/

#include "maya_local.h"

#include "../core/rapidxml/rapidxml_ext.hpp"
#include "../core/rapidxml/rapidxml_print.hpp"
using namespace rapidxml;

/*-----------------------------------------------------------------------------
	Maya animation export :
-----------------------------------------------------------------------------*/

ExportAnimations::ExportAnimations()	{ } 
ExportAnimations::~ExportAnimations() { } 
MStatus ExportAnimations::redoIt()				{	return MS::kSuccess;	} 
MStatus ExportAnimations::undoIt()				{	return MS::kSuccess;	} 
bool	ExportAnimations::isUndoable() const	{	return false;			} 
void*	ExportAnimations::creator()				{	return new ExportAnimations(); } 

void	ParseConnectedCurves( int minTime, int maxTime, IPxAnimTrack track, uint curve_index, const MDagPath &dagPath );
uint	GetParentDagPathIndex( const MDagPathArray &dagPathArray, const MDagPath &child );


//
//	GetParentDagPathIndex
//
uint GetParentDagPathIndex( const MDagPathArray &dagPathArray, const MDagPath &child )
{
	MDagPath	parent	=	child;
	parent.pop();
	
	for (uint i=0; i<dagPathArray.length(); i++) {
		if ( dagPathArray[i] == parent ) {
			return i;
		}
	}
	return -1;
}


//
//	ExportAnimations::doIt
//
MStatus ExportAnimations::doIt( const MArgList& ) 
{ 
	//	load selection :
	MSelectionList activeList;
	MGlobal::getActiveSelectionList( activeList );
	MItSelectionList iter( activeList );
	iter.reset();
	
	MAnimControl	animControl;
	
	

	//	
	//	get min and max time :
	//
	MTime	minTime	=	animControl.minTime();
	MTime	maxTime	=	animControl.maxTime();
	LOGF("Animation control min/max time: %g / %g", minTime.value(), maxTime.value() );
	int	minTimeInt	=	(int)floor(minTime.value()+0.5);
	int	maxTimeInt	=	(int)floor(maxTime.value()+0.5);
	int timeLength	=	maxTimeInt - minTimeInt;
	LOGF("Animation length : %d", timeLength);
	
	
	//
	//	check selection :
	//
	if (activeList.length()!=1) {
		MGlobal::displayError("Select one root joint");
		return MS::kFailure;
	}
	
	MDagPath	dagPath;
	MObject		component;
	MObject		root;
	
	iter.getDagPath( dagPath, component );	
	
	LOGF( "Saving animation track for: '%s'", dagPath.fullPathName().asChar() );

	//MGlobal::executeCommand(
	MString	bakeCommand	=	va("bakeResults -t \"%d:%d\" -sb 1 -hi below -shape true {\"%s\"};", minTimeInt, maxTimeInt, dagPath.fullPathName().asChar() );
	LOGF("bake command : %s", bakeCommand.asChar());
	MGlobal::executeCommand( bakeCommand, false, true );

	//	bakeResults -simulation true -t "1:24" -hierarchy below -sampleBy 1 
	//	-disableImplicitControl false -preserveOutsideKeys true -sparseAnimCurveBake false 
	//	-controlPoints false -shape true {"camera1"};

	
	root	=	dagPath.node();
	
	MFn::Type	type	=	MFn::kInvalid;;
	
	if (root.hasFn( MFn::kTransform )) {
		type	=	MFn::kTransform;
	}
	if (root.hasFn( MFn::kJoint )) {
		type	=	MFn::kJoint;
	}

	if (type==MFn::kInvalid) {
		MGlobal::displayError("Selected object is not a joint or transform");
		MGlobal::executeCommand( "undo", false, true );
		return MS::kFailure;
	}
	
	//
	//	iterate and get all joints in hierarchy an put them in the array :
	//
	MItDag	dagIter;
	dagIter.reset( root, MItDag::kBreadthFirst, type );
	
	MDagPathArray	dagPathArray;
	
	for ( ; !dagIter.isDone(); dagIter.next() ) {
		
		if ( dagIter.item().apiType()!=type ) {
			continue;
		}
	
		dagIter.getPath( dagPath );
		dagPathArray.append( dagPath );
	}


	IPxAnimTrack	anim_track	=	ge()->CreateAnimTrack();
	anim_track->SetTrackSize( dagPathArray.length(), timeLength );
	
	//
	//	process joints :
	//
	for ( uint i=0; i<dagPathArray.length(); i++) {
		LOGF("  %s", dagPathArray[i].fullPathName().asChar());
												  
		anim_track->SetCurveName( i, dagPathArray[i].partialPathName().asChar() );
		anim_track->SetCurveParent( i, GetParentDagPathIndex( dagPathArray, dagPathArray[i] ) );
		
		ParseConnectedCurves( minTimeInt, maxTimeInt, anim_track, i, dagPathArray[i] );
	}
	
	
	//
	//	write XML :
	//
	MString	pathToSave	=	MFileIO::currentFile();
	int point_index	=	pathToSave.rindex('.');
	pathToSave		=	pathToSave.substring(0, point_index);
	pathToSave		+=	MString("eax");
	
	LOGF("Path to save : %s", pathToSave.asChar() );
	
	xml_document<>	xdoc;
	xml_node<>		*xanimation			=	xdoc.allocate_node(node_element, "animation");
	
	xdoc.append_node( xanimation );	
	
	anim_track->WriteXML( xanimation );
	
	LOGF("Writing XML file...\r\n");

	//	Write xml file :
	try {
		ofstream	out_file;
		out_file.open(pathToSave.asChar());
		out_file << xdoc;
		out_file.close();
		
	} catch (exception &e) {
		MGlobal::displayWarning((const char*)va("Cann`t write '%s'", pathToSave.asChar()));
		MGlobal::displayWarning(e.what());
		return MStatus::kFailure;
	}

	LOGF("Done.\r\n");
	MGlobal::executeCommand( "undo", false, true );

    return MS::kSuccess; 
} 


//
//	SampleConnectedCurve
//
void SampleConnectedCurve( int minTime, int maxTime, MPlug connectedTo, std::vector<float> &values, const MString &name )
{
	MPlugArray	plugArray;

	if ( connectedTo.connectedTo( plugArray, true, true ) ) {
	
		for (uint i=0; i<plugArray.length(); i++) {
			MObject	node	=	plugArray[i].node();
			if (!node.hasFn(MFn::kAnimCurve)) {
				continue;
			}
			
			//LOGF("connected curve: %s", name.asChar());
			
			MFnAnimCurve	animCurve( node );
			
			for (int t=minTime; t<maxTime; t++) {
				//LOGF("...%d : %g",  t, animCurve.evaluate( MTime( (double)t )));
				values[t - minTime] = animCurve.evaluate( MTime( (double)t ) );
			}
			
			break;
		}
	}
}


//
//	ParseConnectedCurves
//
void ParseConnectedCurves( int minTime, int maxTime, IPxAnimTrack track, uint curve_index, const MDagPath &dagPath )
{
	MObject	object		=	dagPath.node();
	MFnDependencyNode	dgNode( object );
	
	MFnTransform	transform( object );
	
	MTransformationMatrix::RotationOrder	order	=	transform.rotationOrder();
	
	MPlug	translateX	( object, dgNode.attribute("translateX") );
	MPlug	translateY	( object, dgNode.attribute("translateY") );
	MPlug	translateZ	( object, dgNode.attribute("translateZ") );
	MPlug	rotateX		( object, dgNode.attribute("rotateX") 	 );
	MPlug	rotateY		( object, dgNode.attribute("rotateY")	 );
	MPlug	rotateZ		( object, dgNode.attribute("rotateZ")	 );
	
	std::vector<float>	txc;	txc.resize( track->GetTrackLength() );
	std::vector<float>	tyc;	tyc.resize( track->GetTrackLength() );
	std::vector<float>	tzc;	tzc.resize( track->GetTrackLength() );
	std::vector<float>	rxc;	rxc.resize( track->GetTrackLength() );
	std::vector<float>	ryc;	ryc.resize( track->GetTrackLength() );
	std::vector<float>	rzc;	rzc.resize( track->GetTrackLength() );

	//
	//	write static values :
	//	
	for (uint i=0; i<track->GetTrackLength(); i++) {
		txc[i]	=	translateX.asFloat();
		tyc[i]	=	translateY.asFloat();
		tzc[i]	=	translateZ.asFloat();
		rxc[i]	=	rotateX.asFloat();
		ryc[i]	=	rotateY.asFloat();
		rzc[i]	=	rotateZ.asFloat();
	}
	
	//
	//	write animated values :
	//	
	SampleConnectedCurve( minTime, maxTime, translateX	, txc, "translateX" );
	SampleConnectedCurve( minTime, maxTime, translateY	, tyc, "translateY" );
	SampleConnectedCurve( minTime, maxTime, translateZ	, tzc, "translateZ" );
	SampleConnectedCurve( minTime, maxTime, rotateX		, rxc, "rotateX" );
	SampleConnectedCurve( minTime, maxTime, rotateY		, ryc, "rotateY" );
	SampleConnectedCurve( minTime, maxTime, rotateZ		, rzc, "rotateZ" );

	for (uint i=0; i<track->GetTrackLength(); i++) {
		float tx	=	txc[i];
		float ty	=	tyc[i];
		float tz	=	tzc[i];
		float rx	=	rxc[i];
		float ry	=	ryc[i];
		float rz	=	rzc[i];
		
		EQuaternion qrx	=	EQuaternion::RotateAroundAxis( rx, EVector::kX );
		EQuaternion qry	=	EQuaternion::RotateAroundAxis( ry, EVector::kY );
		EQuaternion qrz	=	EQuaternion::RotateAroundAxis( rz, EVector::kZ );
		EQuaternion qr;
		
		if (order==MTransformationMatrix::kXYZ)	qr	=	qrz * qry * qrx;
		if (order==MTransformationMatrix::kYZX)	qr	=	qrx * qrz * qry;
		if (order==MTransformationMatrix::kZXY)	qr	=	qry * qrx * qrz;
		if (order==MTransformationMatrix::kXZY)	qr	=	qry * qrz * qrx;
		if (order==MTransformationMatrix::kYXZ)	qr	=	qrz * qrx * qry;
		if (order==MTransformationMatrix::kZYX)	qr	=	qrx * qry * qrz;
		
		track->SetSample( curve_index, i, EPoint(tx,ty,tz), qr.Normalize() );
	}
}









